<?php
class Model{
		
	protected $db_config = '';
	
	protected $db = '';
	
	protected $db_setting = 'default';
	
	protected $table_name = '';
	
	public $db_tablepre = '';
	
	private $_errors=array();	// attribute name => array of errors
	
	private $_validators;  		// validators
	
	//翻页数组
	public $pages;
	
	public function __construct(){		
		if(!isset($this->db_config[$this->db_setting])){
			$this->db_setting = 'default';
		}
		$this->table_name = $this->db_config[$this->db_setting]['tablepre'].$this->table_name;
		$this->db_tablepre = $this->db_config[$this->db_setting]['tablepre'];		
		$this->db = DBFactory::get_instance($this->db_config)->get_database($this->db_setting);
	}
	
	/**
	 * 直接执行sql查询
	 * @param $sql							查询sql语句
	 * @return	boolean/query resource		如果为查询语句，返回资源句柄，否则返回true/false
	 */
	final public function query($sql){
		return $this->db->query($sql);
	}
	
	/**
	 * 查询多条数据
	 * @param $where
	 * @param $order
	 * @param $page     页数
	 * @param $pagesize 每页显示数
	 * @return unknown_type
	 */
	final public function listinfo($where = '', $data, $order = '', $page = 1, $pagesize = 20){
		$where = $this->tosqls($where);
		$total_rows = $this->count($where); //数据总数
		$page = max(intval($page), 1);
		$offset = $pagesize * ($page - 1);  //之前数据
		$total_pages = ceil($total_rows/$pagesize);  //总页数
		$this->pages = array('curr_page'=>$page,'page_size'=>$pagesize,'total_rows'=>$total_rows,'total_pages'=>$total_pages);
		if($total_rows > 0){
			return $this->select($where, $data, "$offset, $pagesize", $order, '');
		} else {
			return array();
		} 		
	}
	
	/**
	 * 执行sql查询
	 * @param $where 		查询条件[例`name`='$name']
	 * @param $data 		需要查询的字段值[例`name`,`gender`,`birthday`]
	 * @param $limit 		返回结果范围[例：10或10,10 默认为空]
	 * @param $order 		排序方式	[默认按数据库默认方式排序]
	 * @param $group 		分组方式	[默认为空]
	 * @return array		查询结果集数组
	 */
	final public function select($where = '', $data = '*', $limit = '', $order = '', $group = ''){
		if(is_array($where)) $where = $this->tosqls($where);
		return $this->db->select($data, $this->table_name, $where, $limit, $order, $group);
	}
	
	/**
	 * 获取单条记录查询
	 * @param $where 		查询条件
	 * @param $data 		需要查询的字段值[例`name`,`gender`,`birthday`]
	 * @param $order 		排序方式	[默认按数据库默认方式排序]
	 * @param $group 		分组方式	[默认为空]
	 * @return array/null	数据查询结果集,如果不存在，则返回空
	 */
	final public function get_one($where = '', $data = '*', $order = '', $group = ''){
		if (is_array($where)) $where = $this->tosqls($where);
		return $this->db->get_one($data, $this->table_name, $where, $order, $group);
	}
	
	/**
	 * 执行添加记录操作
	 * @param $data 		要增加的数据，参数为数组。数组key为字段值，数组值为数据取值
	 * @param $return_insert_id 是否返回新建ID号
	 * @param $replace 是否采用 replace into的方式添加数据
	 * @return boolean
	 */
	final public function insert($data, $return_insert_id = false, $replace = false){
		if(!$this->validate($data)){
			return false;
		} else{
			return $this->db->insert($data, $this->table_name, $return_insert_id, $replace);
		}		
	}
	
	/**
	 * 获取最后一次添加记录的主键号
	 * @return int 
	 */
	final public function insert_id() {
		return $this->db->insert_id();
	}
	
	/**
	 * 执行更新记录操作
	 * @param $data 		要更新的数据内容，参数可以为数组也可以为字符串，建议数组。
	 * 						为数组时数组key为字段值，数组值为数据取值
	 * 						为字符串时[例：`name`='ps',`hits`=`hits`+1]。
	 *						为数组时[例: array('name'=>'ps','password'=>'123456')]
	 *						数组的另一种使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1
	 * @param $where 		更新数据时的条件,可为数组或字符串
	 * @return boolean
	 */
	final public function update($data, $where = ''){
		if(is_array($where)) $where = $this->tosqls($where);
		return $this->db->update($data, $this->table_name, $where);
	}
	
	/**
	 * 执行删除记录操作
	 * @param $where 		删除数据条件,不充许为空。
	 * @return boolean
	 */
	final public function delete($where) {
		if (is_array($where)) $where = $this->tosqls($where);
		return $this->db->delete($this->table_name, $where);
	}
	
	/**
	 * 计算记录数
	 * @param string/array $where 查询条件
	 */
	final public function count($where = ''){
		$r = $this->get_one($where, "COUNT(*) AS num");
		return $r['num'];
	}
	
	/**
	 * 将数组转换为SQL语句
	 * @param array $where 要生成的数组
	 * @param string $font 连接串。
	 */
	final public function tosqls($where, $font = ' AND '){
		if(is_array($where)){
			$sql = '';
			foreach ($where as $key => $val) {
				$sql .= $sql ? " $font `$key` = '$val'" : "`$key` = '$val'";
			}
			return $sql;
		} else {
			return $where;
		}
	}
	
	public function rules(){
		return array();
	}
	
	public function attributeLabels()
	{
		return array();
	}
	
	/**
	 * Returns the validators applicable to the current 
	 */
	public function validate($value,$attributes = null, $clearErrors = true){
		if($clearErrors){
			$this->clearErrors();
		}
		foreach ($this->getValidators() as $validator) {
			$validator->validate($this,$attributes,$value);
		}
		return !$this->hasErrors();
	}
	
	/**
	 * 取得验证
	 * Enter description here ...
	 */
	public function getValidators(){
		if($this->_validators === null){			
			$this->_validators=$this->createValidators();
		}
		$validators=array();
		foreach($this->_validators->_d as $validator)
		{
			$validators[]=$validator;
		}
		return $validators;
	}
	
	/**
	 * 生成验证器
	 * Enter description here ...
	 */
	public function createValidators(){
		$validators = new CList();
		foreach ($this->rules() as $rule) {
			if(isset($rule[0],$rule[1])){
				$validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
			}
		}
		return $validators;
	}
	
	/**
	 * 清理错误信息
	 * Enter description here ...
	 */
	public function clearErrors(){
		$this->_errors = array();
	}
	
	/**
	 * Adds a new error to the specified attribute.
	 * @param string $attribute attribute name
	 * @param string $error new error message
	 */
	public function addError($attribute,$error){
		$this->_errors[$attribute][] = $error;
	}
	
	/**
	 * Returns the errors for all attribute or a single attribute.
	 * @param string $attribute attribute name. Use null to retrieve errors for all attributes.
	 * @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
	 */
	public function getErrors($attribute=null)
	{
		if($attribute===null)
			return $this->_errors;
		else
			return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
	}
	/**
	 * Returns a value indicating whether there is any validation error.
	 * @param string $attribute attribute name. Use null to check all attributes.
	 * @return boolean whether there is any error.
	 */
	public function hasErrors(){
		return $this->_errors !== array();	
	}
}
